# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         testcase_result.py
# Description:  
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2019/11/21 11:13
# -------------------------------------------------------------------------------
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import status
from rest_framework.filters import OrderingFilter
from rest_framework.generics import DestroyAPIView
from rest_framework.mixins import CreateModelMixin
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ReadOnlyModelViewSet, GenericViewSet

from apps.BasicAuthService.models import Role
from apps.HttpAutoTestService.filters import TestcaseResultFilter
from apps.HttpAutoTestService.models import TestcaseResult
from apps.HttpAutoTestService.serializers import TestcaseResultSerializer

__all__ = ['TestcaseResultVersionAPIView', 'TestcaseResultListViewSet', 'TestcaseResultViewSet',
           'TestcaseResultBatchDestroyAPIView']


class TestcaseResultVersionAPIView(APIView):
    """
    测试用例结果最新的10个版本号
    """

    def get(self, request, *args, **kwargs):
        user = request.user
        testcase_results = TestcaseResult.objects.filter(is_deleted=False, testsuite_result_id__isnull=True)
        if not Role.objects.filter(code='SUPERADMIN', user=user, is_deleted=False):
            testcase_results = testcase_results.filter(project__members=user)
        data = testcase_results.order_by('-version').values('version').distinct()[:10]
        for item in data:
            res = TestcaseResult.objects.filter(
                version=item.get('version'), is_deleted=False
            ).values_list('status', flat=True)
            res = list(set(res))
            if len(res) == 1:
                item['status'] = res[0]
            else:
                item['status'] = 'PARTIAL_PASS'
        return Response(status=status.HTTP_200_OK, data=data, content_type='application/json')


class TestcaseResultListViewSet(ReadOnlyModelViewSet):
    """
    用例结果列表
    """
    serializer_class = TestcaseResultSerializer
    filter_backends = (DjangoFilterBackend, OrderingFilter)
    filter_class = TestcaseResultFilter
    ordering_fields = ['execute_time', 'version']

    def get_queryset(self):
        user = self.request.user
        testcase_results = TestcaseResult.objects.filter(is_deleted=False)
        if not Role.objects.filter(code='SUPERADMIN', user=user, is_deleted=False):
            testcase_results = testcase_results.filter(project__members=user)
        return testcase_results


class TestcaseResultViewSet(CreateModelMixin, GenericViewSet):
    """
    用例结果创建
    """
    queryset = TestcaseResult.objects.filter(is_deleted=False)
    serializer_class = TestcaseResultSerializer


class TestcaseResultBatchDestroyAPIView(DestroyAPIView):
    """
    用例结果批量删除
    """

    def delete(self, request, *args, **kwargs):
        data = request.data
        permanent = data.get('permanent')  # true：永久(物理)删除，false：临时(逻辑)删除
        testcase_result_ids = data.get('testcaseResults')
        if permanent:
            TestcaseResult.objects.filter(id__in=testcase_result_ids).delete()
            return Response(status=status.HTTP_204_NO_CONTENT)
        TestcaseResult.objects.filter(id__in=testcase_result_ids).update(is_deleted=True)
        return Response(status=status.HTTP_200_OK, data='临时删除成功', content_type='application/json')
